package com.pt5.pthouduan.entity;

import com.turn.ttorrent.tracker.TrackedTorrent;
import org.springframework.beans.factory.annotation.Autowired;

import java.io.UnsupportedEncodingException;
import java.lang.reflect.InvocationHandler;
import java.lang.reflect.Method;
import java.lang.reflect.Proxy;

public class TrackedTorrentProxy implements InvocationHandler{
    private final TrackedTorrent target;
    private volatile String passkey;
    private final StatsRecorder statsRecorder;
    private TrackedTorrentProxy(TrackedTorrent target, String passkey, StatsRecorder statsRecorder){
        this.target = target;
        this.passkey = passkey;
        this.statsRecorder = statsRecorder;
    }
    public void setCurrentPasskey(String passkey){
        this.passkey = passkey;
    }
    @Override
    public Object invoke(Object proxy, Method method, Object[] args) throws Throwable {
        //拦截update方法
        if("update".equals(method.getName())){
            handleUpdate(args);
        }
        return method.invoke(target, args);
    }
    private void handleUpdate(Object[] args) throws UnsupportedEncodingException{
        //解析参数
        long uploaded = (long) args[5];
        long downloaded = (long) args[6];
        String ip = (String) args[3];
        int port = (int) args[4];
        String peerId = (String) args[2];
        if(this.passkey == null){
            return;
        }

        //记录统计信息
        statsRecorder.recordStats(
                passkey,
                target.getHexInfoHash(),
                ip,
                port,
                peerId,
                uploaded,
                downloaded
        );
    }
    //创建代理实例
    public static TrackedTorrent createProxy(TrackedTorrent original, String passkey,StatsRecorder statsRecorder){
        return (TrackedTorrent) Proxy.newProxyInstance(
                original.getClass().getClassLoader(),
                new Class[]{TrackedTorrent.class},
                new TrackedTorrentProxy(original, passkey, statsRecorder)
        );
    }

}
